import util, {formatDate} from "../../../utils/util";
import network from "../../../utils/network";
import Validate from "../../../utils/validate";
import {multiply} from "../../../utils/amount";

const app = getApp()
Component({
    ready() {
        const hasTabs = util.hasBtnRights([
            'workLog-cur-month-fill-visit-btn',
            'workLog-cur-month-fill-estimate-btn',
            'workLog-cur-month-fill-next-time-btn',
            'workLog-cur-month-fill-comments-btn',
            'workLog-cur-month-fill-reason-btn'
        ]);
        this.setData({
            fill_visit_btn: hasTabs[0],
            fill_estimate_btn: hasTabs[1],
            fill_next_time_btn: hasTabs[2],
            fill_comments_btn: hasTabs[3],
            fill_reason_btn: hasTabs[4],
        })
        this.initValidateNextVisit()
        this.initValidateSignContract()
    },
    properties: {
        list: {
            type: Array,
            value: []
        }
    },
    data: {
        requestUrl: app.api.followListByCustomerId,
        requestParams: {
            customer_id: -1
        },
        nextVisitDialogShow: false,
        nextVisit: {
            id: null,// 客户id
            date: null,
            purpose: null
        },
        tmpCustomerId: -1,
        followHistoryDialogShow: false,
        commentsHistoryList: [],
        commentsHistoryDialogShow: false,
        beforeClose: (e) => {
            return e === 'cancel'
        },
        comments: {
            customer_id: -1,
            comments: null
        },
        dialogShow: false,
        reasons: {
            customer_estimate_record_id: -1,
            reasons_for_not_cooperating: null
        },
        fill_visit_btn: false,
        fill_estimate_btn: false,
        fill_next_time_btn: false,
        fill_comments_btn: false,
        fill_reason_btn: false,
        reasonsDialogShow: false,
        validateNextVisit: {},
        calendarShow: false,
        addDialogShow: false,
        signContract: {
            record_id: '',
            target_record_id: '',
            id: '',// 客户id
            week_id: '',
            week_name: '',// 周显示文本
            transaction_evaluation: '',// 成交预估
            quota: '',// 成交金额
        },
        selectSignTimeLoading: false,
        weekArr: [],
        source_week_arr: [],
        selectWeekPopup: false,
        validateSignContract: {}
    },
    methods: {
        onChange(e) {
            if (e.target.dataset.type === '1') {
                let index = e.target.dataset.index
                if (this.data.list[index].active.length) {
                    this.data.list[index].active = []
                } else {
                    this.data.list[index].active = ['1']
                }
                this.setData({
                    list: this.data.list
                })
            } else {
                let index = e.target.dataset.index
                if (this.data.list[index].activeNames.length) {
                    this.data.list[index].activeNames = []
                } else {
                    this.data.list[index].activeNames = ['1']
                }
                this.setData({
                    list: this.data.list
                })
            }
        },
        showAddRecordDialog(e) {
            this.setData({
                tmpCustomerId: e.target.dataset.id,
            })
            this.selectComponent("#AddFollowRecordDialog").showDialog()
        },
        // 验证函数
        initValidateSignContract() {
            const rules = {
                id: {
                    required: true
                },
                week_id: {
                    required: true
                },
                quota: {
                    required: true,
                },
                transaction_evaluation: {
                    required: true
                },
            }
            const messages = {
                id: {
                    required: '请选择客户'
                },
                week_id: {
                    required: '请选择签约时间'
                },
                quota: {
                    required: '请输入签约金额',
                },
                transaction_evaluation: {
                    required: '请选择签约预估'
                },
            }
            this.data.validateSignContract = new Validate(rules, messages)
        },
        initValidateNextVisit() {
            const rules = {
                id: {
                    required: true
                },
                date: {
                    required: true
                },
                purpose: {
                    required: true,
                }
            }
            const messages = {
                id: {
                    required: '请选择客户'
                },
                date: {
                    required: '请选择下次拜访时间'
                },
                purpose: {
                    required: '请输入拜访目的',
                }
            }
            this.data.validateNextVisit = new Validate(rules, messages)
        },
        addSuccess() {
            this.setData({
                tmpCustomerId: -1
            })
        },
        showAddComments(e) {
            this.setData({
                dialogShow: true,
                'comments.customer_id': e.target.dataset.id
            })
        },
        showReasonsDialog(e) {
            this.setData({
                reasonsDialogShow: true,
                reasons: {
                    customer_estimate_record_id: e.target.dataset.item.id,
                    reasons_for_not_cooperating: e.target.dataset.item.reasons_for_not_cooperating
                }
            })
        },
        showHistoryRecordDialog(e) {
            this.setData({
                'requestParams.customer_id': e.target.dataset.id,
                followHistoryDialogShow: true
            })
            this.selectComponent("#follow-list").getList()
        },
        preventTouchMove() {

        },
        closeFollowHistoryDialog() {
            this.setData({
                followHistoryDialogShow: false
            })
        },
        closeCommentsHistoryDialog() {
            this.setData({
                commentsHistoryDialogShow: false
            })
        },
        showCommentsHistoryDialog(e) {
            this.setData({
                tmpCustomerId: e.target.dataset.id,
                commentsHistoryDialogShow: true
            })
            this.getCommentsHistoryData()
        },
        getCommentsHistoryData() {
            const that = this
            util.showLoading('加载中');
            network.GET({
                uri: app.api.visitCommentsPage,
                params: {customer_id: this.data.tmpCustomerId},
                success: (res) => {
                    that.setData({
                        commentsHistoryList: res.data.records
                    })
                    util.hideLoading();
                },
                fail: (res) => {
                    util.hideLoading();
                }
            })
        },
        onDialogClose() {
            this.setData({
                comments: {
                    customer_id: -1,
                    comments: null
                },
                dialogShow: false
            })
        },
        onDialogConfirm() {
            if (this.data.comments.customer_id !== -1 && !this.data.comments.customer_id) {
                util.showToast('系统错误')
                return
            }
            if (!this.data.comments.comments) {
                util.showToast('请填写批注')
                return
            }
            util.showLoading('加载中');
            network.reqPromise('POST', {
                uri: app.api.fillAnnotation + '?customer_id=' + this.data.comments.customer_id + '&comments=' + this.data.comments.comments
            }).then(res => {
                util.hideLoading()
                this.onDialogClose()
                this.triggerEvent('reload')
            }).catch(() => {
                util.hideLoading()
            })
        },
        // 输入框输change
        onInputChange(e) {
            const key = e.target.dataset.key;
            this.setData({
                [key]: e.detail
            })
        },
        onReasonsDialogClose() {
            this.setData({
                reasonsDialogShow: false,
                reasons: {
                    customer_estimate_record_id: -1,
                    reasons_for_not_cooperating: null
                }
            })
        },
        onReasonsDialogConfirm() {
            if (this.data.reasons.customer_estimate_record_id !== -1 && !this.data.reasons.customer_estimate_record_id) {
                util.showToast('系统错误')
                return
            }
            if (!this.data.reasons.reasons_for_not_cooperating) {
                util.showToast('请输入原因')
                return
            }
            util.showLoading('加载中');
            network.reqPromise('POST', {
                uri: app.api.fillReasonsForNotCooperating,
                params: [this.data.reasons]
            }).then(res => {
                util.hideLoading()
                this.onReasonsDialogClose()
                this.triggerEvent('reload')
            }).catch(() => {
                util.hideLoading()
            })
        },
        showNextVisitDialog(e) {
            this.setData({
                'nextVisit.id': e.target.dataset.id,
                nextVisitDialogShow: true
            })
        },
        showCalendar() {
            this.setData({
                calendarShow: true
            })
        },
        closeNextVisitDialog() {
            this.setData({
                nextVisitDialogShow: false,
                nextVisit: {
                    id: null,// 客户id
                    date: null,
                    purpose: null
                }
            })
        },
        confirmNextVisitDialog() {
            if (!this.data.validateNextVisit.checkForm(this.data.nextVisit)) {
                util.showToast(this.data.validateNextVisit.errorList[0].msg)
            } else {
                util.showLoading('添加中')
                network.reqPromise('POST', {
                    uri: app.api.addNextVisitDate,
                    params: this.data.nextVisit
                }).then(res => {
                    util.hideLoading()
                    util.showToast('添加成功')
                    this.setData({
                        nextVisitDialogShow: false
                    })
                    this.closeNextVisitDialog()
                }).catch(() => {
                    util.hideLoading()
                    util.showToast('添加失败')
                })
            }
        },
        onCalendarConfirm(e) {
            this.setData({
                'nextVisit.date': formatDate(e.detail),
                calendarShow: false
            })
        },
        onCalendarClose() {
            this.setData({
                calendarShow: false
            })
        },

        closeAddDialog() {
            this.setData({
                addDialogShow: false,
                signContract: {
                    record_id: '',
                    target_record_id: '',
                    id: '',// 客户id
                    week_id: '',
                    week_name: '',// 周显示文本
                    transaction_evaluation: '',// 成交预估
                    quota: '',// 成交金额
                }
            })
        },
        confirmAddDialog() {
            if (!this.data.validateSignContract.checkForm(this.data.signContract)) {
                util.showToast(this.data.validateSignContract.errorList[0].msg)
            } else {
                util.showLoading('操作中')
                network.reqPromise('POST', {
                    uri: app.api.addSigningTime,
                    params: this.data.signContract
                }).then(res => {
                    util.hideLoading()
                    util.showToast('操作成功')
                    this.setData({
                        addDialogShow: false
                    })
                    this.closeAddDialog()
                }).catch(() => {
                    util.hideLoading()
                    util.showToast('操作失败')
                })
            }
        },
        confirmWeek(e) {
            this.setData({
                'signContract.week_id': e.detail.value.id,
                'signContract.week_name': e.detail.value.name,
                selectWeekPopup: false
            })
        },
        showWeekPop() {
            this.setData({
                selectWeekPopup: true
            })
        },
        cancelWeekPop() {
            this.setData({
                selectWeekPopup: false
            })
        },
        changeSearch(e) {
            let filter = this.data.source_week_arr.filter(item => item.name.indexOf(e.detail) >= 0);
            this.setData({
                searchValue: e.detail,
                weekArr: filter
            })
        },
        onRadioChange(e) {
            this.setData({
                'signContract.transaction_evaluation': e.detail
            })
        },
        showAddDialog(e) {
            this.setData({
                'signContract.id': e.target.dataset.item.id,
                selectSignTimeLoading: true,
            })
            if (e.target.dataset.type === '2') {
                this.setData({
                    'signContract.record_id': e.target.dataset.tmp.id,
                    'signContract.target_record_id': e.target.dataset.tmp.target_record_id,
                    'signContract.quota': multiply(e.target.dataset.tmp.quota, 10000),
                    'signContract.transaction_evaluation': e.target.dataset.tmp.transaction_evaluation + '',
                    'signContract.week_id': e.target.dataset.tmp.week_id,
                    'signContract.week_name': e.target.dataset.tmp.week_name
                })
            }
            network.reqPromise("GET", {
                uri: app.api.getYearWeekList,
                params: {customer_id: this.data.signContract.id, record_id: this.data.signContract.record_id}
            }).then(res => {
                res.data.forEach(item => {
                    item.name = item.begin_date + '~' + item.end_date
                })
                this.setData({
                    weekArr: res.data,
                    source_week_arr: res.data,
                    selectSignTimeLoading: false
                })
            }).catch(() => {
                util.showToast('获取数据失败')
            })
            this.setData({
                addDialogShow: true
            })
        },
    }
});
